package org.proyectosinapsis.Sinapsis;

/**
 * User: Alexander Simoes
 * Company: CoralVision Systems
 * Date: 9/12/12
 */

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import org.proyectosinapsis.Sinapsis.library.JSONParser;

import java.util.ArrayList;
import java.util.List;

//ToDo: get rid of all warnings
//Check if it's a dr or a patient
public class LoginActivity extends Activity {

	//Progress Dialog
	private ProgressDialog pDialog;

	//Function that checks if all EditText in the layout are not empty
	//It displays a floating text asking the user for the input
	//True if it finds at least one that is empty
	private boolean checkForm() {

		ViewGroup group = (ViewGroup) findViewById(R.id.loginForm);
		String errorMsg = getString(R.string.emptyForm);
		int strLenght = errorMsg.length();

		for (int i = 0, count = group.getChildCount(); i < count; ++i) {
			View view = group.getChildAt(i);
			if (view instanceof EditText) {
				String str = ((EditText)view).getText().toString();
				if (str.trim().equals("")) {
					errorMsg = errorMsg + "\n" + (view).getTag().toString();
				}
			}
		}

		if (errorMsg.length()!=strLenght) {
			Toast.makeText(this, errorMsg, Toast.LENGTH_SHORT).show();
			return true;
		}

		return false;
	}

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // setting default screen to login.xml
        setContentView(R.layout.login);

        TextView registerScreen = (TextView) findViewById(R.id.link_to_register);
        TextView recPass = (TextView) findViewById(R.id.link_recover_password);
	    Button login = (Button) findViewById(R.id.buttonLogin);

        // Listening to register new account link
        registerScreen.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                // Switching to Register screen
                Intent i = new Intent(getApplicationContext(), RegisterActivity.class);
                startActivity(i);
            }
        });

        // Listening to recover password link
	    recPass.setOnClickListener(new View.OnClickListener() {

		    public void onClick(View v) {
			    // Switching to Register screen
			    Intent i = new Intent(getApplicationContext(), RecoverPasswordActivity.class);
			    startActivity(i);
		    }
	    });

	    // Listening to login button
	    login.setOnClickListener(new View.OnClickListener() {

		    public void onClick(View v) {
			    //Check that form isn't empty
/*			    ConnectivityManager connMgr = (ConnectivityManager)                    //ToDo:CHECK THE NETWORK CONNECTION
				    getSystemService(Context.CONNECTIVITY_SERVICE);
			    NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
			    if (networkInfo != null && networkInfo.isConnected()) {
				    // fetch data
			    } else {
				    // display error
			    }*/

			    if (checkForm()){
				    return;
			    }

			    //Trying to login
			    //LLAMADA ASINCRONA PARA BAJAR CONSULTAR LA BD DE SINAPSIS
			    new HttpLogin().execute("");
		    }
	    });
    }

	//Class that makes the http request in a different UI String and checks if user exists
	private class HttpLogin extends AsyncTask<String, String, String> {            //ToDo: Return user data

		private boolean error = false;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(LoginActivity.this);
			pDialog.setMessage(getString(R.string.loginIn));
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
		}

		@Override
		protected String doInBackground(String... args) {
			JSONParser jParser = new JSONParser();
			String url = getString(R.string.URL_SINAPSIS_ANDROID);
			String tagSuccess = getString(R.string.TAG_SUCCESS);
			String username = ((EditText) findViewById(R.id.loginUsername)).getText().toString();
			String password = ((EditText) findViewById(R.id.loginPassword)).getText().toString();

			//Building Parameters
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("username", username));
			params.add(new BasicNameValuePair("password", password));
			params.add(new BasicNameValuePair("tag", "login"));

			JSONObject json = jParser.getJSONFromUrl(url, params);

			//JSON response in LOG CAT
			// Log.d("Login: ", json.toString());
			try {

				//
				int success = json.getInt(tagSuccess);
			//	String str = "";

				if (success == 1) {
//					JSONArray userArray = json.getJSONArray("user"); // JSON Array
				//	JSONObject user = json.getJSONObject("user"); // USER  ToDo: Check what to do with response
				//	str = " " + username + " " + user.getString("pid") + " " + user.getString("name"); //pasar a actividad
				} else {
					error = true;
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
			return "Done HttpLogin"; //ToDo: decide the return values (boolean, or string, or wtv)
		}

		@Override
		protected void onPostExecute(String file_url) {
			// dismiss the dialog once done
			pDialog.dismiss();
			if (error) {
				Toast.makeText(LoginActivity.this,getString(R.string.loginError),Toast.LENGTH_SHORT).show();
			} else {
				//Toast.makeText(LoginActivity.this,"LOGUEADO",Toast.LENGTH_SHORT).show();
				//INICIO PANTALLA DEL PACIENTE O MEDICO ToDo: Check if it is a patient or a doctor
				Intent i = new Intent(getApplicationContext(), PatientHomeActivity.class);
				startActivity(i);
			}
		}
	}
}


/*public class AllProductsActivity extends ListActivity {       //TAKE FROM HERE ASYNCHRONOUS CALLS

	// Progress Dialog
	private ProgressDialog pDialog;

	// Creating JSON Parser object
	JSONParser jParser = new JSONParser();

	ArrayList<HashMap<String, String>> productsList;

	// url to get all products list
	private static String url_all_products = "http://api.androidhive.info/android_connect/get_all_products.php";

	// JSON Node names
	private static final String TAG_SUCCESS = "success";
	private static final String TAG_PRODUCTS = "products";
	private static final String TAG_PID = "pid";
	private static final String TAG_NAME = "name";

	// products JSONArray
	JSONArray products = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.all_products);

		// Hashmap for ListView
		productsList = new ArrayList<HashMap<String, String>>();

		// Loading products in Background Thread
		new LoadAllProducts().execute();

		// Get listview
		ListView lv = getListView();

		// on seleting single product
		// launching Edit Product Screen
		lv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
			                        int position, long id) {
				// getting values from selected ListItem
				String pid = ((TextView) view.findViewById(R.id.pid)).getText()
					.toString();

				// Starting new intent
				Intent in = new Intent(getApplicationContext(),
					EditProductActivity.class);
				// sending pid to next activity
				in.putExtra(TAG_PID, pid);

				// starting new activity and expecting some response back
				startActivityForResult(in, 100);
			}
		});

	}

	// Response from Edit Product Activity
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		// if result code 100
		if (resultCode == 100) {
			// if result code 100 is received
			// means user edited/deleted product
			// reload this screen again
			Intent intent = getIntent();
			finish();
			startActivity(intent);
		}

	}

	*//**
	 * Background Async Task to Load all product by making HTTP Request
	 * *//*
	class LoadAllProducts extends AsyncTask<String, String, String> {

		*//**
		 * Before starting background thread Show Progress Dialog
		 * *//*
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(AllProductsActivity.this);
			pDialog.setMessage("Loading products. Please wait...");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
		}

		*//**
		 * getting All products from url
		 * *//*
		protected String doInBackground(String... args) {
			// Building Parameters
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			// getting JSON string from URL
			JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);

			// Check your log cat for JSON reponse
			Log.d("All Products: ", json.toString());

			try {
				// Checking for SUCCESS TAG
				int success = json.getInt(TAG_SUCCESS);

				if (success == 1) {
					// products found
					// Getting Array of Products
					products = json.getJSONArray(TAG_PRODUCTS);

					// looping through All Products
					for (int i = 0; i < products.length(); i++) {
						JSONObject c = products.getJSONObject(i);

						// Storing each json item in variable
						String id = c.getString(TAG_PID);
						String name = c.getString(TAG_NAME);

						// creating new HashMap
						HashMap<String, String> map = new HashMap<String, String>();

						// adding each child node to HashMap key => value
						map.put(TAG_PID, id);
						map.put(TAG_NAME, name);

						// adding HashList to ArrayList
						productsList.add(map);
					}
				} else {
					// no products found
					// Launch Add New product Activity
					Intent i = new Intent(getApplicationContext(),
						NewProductActivity.class);
					// Closing all previous activities
					i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					startActivity(i);
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}

			return null;
		}

		*//**
		 * After completing background task Dismiss the progress dialog
		 * **//*
		protected void onPostExecute(String file_url) {
			// dismiss the dialog after getting all products
			pDialog.dismiss();
			// updating UI from Background Thread
			runOnUiThread(new Runnable() {
				public void run() {
					*//**
					 * Updating parsed JSON data into ListView
					 * *//*
					ListAdapter adapter = new SimpleAdapter(
						AllProductsActivity.this, productsList,
						R.layout.list_item, new String[] { TAG_PID,
						TAG_NAME},
						new int[] { R.id.pid, R.id.name });
					// updating listview
					setListAdapter(adapter);
				}
			});

		}

	}
}*/

/**
 * Background Async Task to Create new product
 * */
/*class CreateNewProduct extends AsyncTask<String, String, String> {

	*//**
	 * Before starting background thread Show Progress Dialog
	 * *//*
	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		pDialog = new ProgressDialog(NewProductActivity.this);
		pDialog.setMessage("Creating Product..");
		pDialog.setIndeterminate(false);
		pDialog.setCancelable(true);
		pDialog.show();
	}

	*//**
	 * Creating product
	 * *//*
	protected String doInBackground(String... args) {
		String name = inputName.getText().toString();
		String price = inputPrice.getText().toString();
		String description = inputDesc.getText().toString();

		// Building Parameters
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("name", name));
		params.add(new BasicNameValuePair("price", price));
		params.add(new BasicNameValuePair("description", description));

		// getting JSON Object
		// Note that create product url accepts POST method
		JSONObject json = jsonParser.makeHttpRequest(url_create_product,
			"POST", params);

		// check log cat fro response
		Log.d("Create Response", json.toString());

		// check for success tag
		try {
			int success = json.getInt(TAG_SUCCESS);

			if (success == 1) {
				// successfully created product
				Intent i = new Intent(getApplicationContext(), AllProductsActivity.class);
				startActivity(i);

				// closing this screen
				finish();
			} else {
				// failed to create product
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}

		return null;
	}

	*//**
	 * After completing background task Dismiss the progress dialog
	 * **//*
	protected void onPostExecute(String file_url) {
		// dismiss the dialog once done
		pDialog.dismiss();
	}

}
}*/